package com.gxa.hualian.web.filter;

import com.gxa.hualian.exception.BusinessException;
import com.gxa.hualian.exception.ExceptionCode;
import com.gxa.hualian.util.StringUtil;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(filterName = "TokenFilter",urlPatterns = "/user")
public class TokenFilter implements Filter {
    @Override
    public void init(FilterConfig config) throws ServletException {
    }

    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        System.out.println("Token权限过滤器开始工作了");


        //当过滤器拦截了请求之后,获取URL/URI
        String requestURI = ((HttpServletRequest) request).getRequestURI();
        //      System.out.println("requestURI:"+requestURI);
        StringBuffer requestURL = ((HttpServletRequest) request).getRequestURL();
//        System.out.println("requestURL:"+requestURL);
        String token=((HttpServletRequest) request).getHeader("token");
        //       System.out.println(token);
        //判断如果是静态
//        String[] ext={".html",".js",".css",".png",".htm",".jsp",".jpg"};
//        for (String s : ext){
//            //放行列表
//            if (requestURI.endsWith(s)){
//                chain.doFilter(request,response);
//            }
//        }
        if (requestURI.startsWith("/static/")){
            chain.doFilter(request,response);
        }
        //如果是/register/login 直接放行
        if (requestURI.endsWith("/register") || requestURI.endsWith("/login")){
            chain.doFilter(request,response);
        }

        //如果带有handlerType为register/login
        String handlerType = ((HttpServletRequest) request).getHeader("handlerType");
        if ("login".equals(handlerType) || "register".equals(handlerType)){
            chain.doFilter(request,response);
        }

        BusinessException businessException = new BusinessException(ExceptionCode.WRONG_TOKEN);
        if(StringUtil.isEmpty(token)){

            request.setAttribute("exception",businessException);
            //利用转发
            request.getServletContext().getRequestDispatcher("/error").forward(request,response);
        }
        //检验token的合法性
        HttpSession session = ((HttpServletRequest) request).getSession();
        Object sysToken=session.getAttribute("token");
        if (token.equals(sysToken)){
            chain.doFilter(request, response);
        }else{
            request.setAttribute("exception",businessException);
            request.getServletContext().getRequestDispatcher("/error").forward(request,response);
        }

        chain.doFilter(request,response);
        System.out.println("Token权限过滤器完成了放行...");
    }
}
